package com.sangananitsolution.fragments;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TimePicker;
import android.widget.Toast;

import com.sangananitsolution.database.UserInfoCRUD;
import com.sangananitsolution.gogoproject.MainPaypalclass;
import com.sangananitsolution.gogoproject.PhotoHandlingClass;
import com.sangananitsolution.gogoproject.PhotoHandlingClassNew;
import com.sangananitsolution.gogoproject.R;

public class MyGarbageSale_CreateNew extends Fragment {
	View view;
	public EditText startdate, starttime, finishtime, unitstreetnumber,
			streetname, suburb, citystarte, postcode, discritpion, state,
			radiosaletypeoneDay, radiosaletypeTwoDay, showstreetaddress,
			typeofgoodsforselling;
	RadioGroup radiogroupsaletype, radiogroupshowaddress;
	RadioButton radiobuttonsalestype, radiobuttonshowaddress;
	String statusof, mesageof;
	ImageView imageView1, imageView2, imageView3, imageView4, imageView5,
			imageView6, imageView7, imageView8, imageView9, imageView10;
	ArrayList<Bitmap> arraylistforimage;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Move back to Mysearch
		view = inflater.inflate(R.layout.mygarbagesalescreatenew, container,
				false);
		arraylistforimage=new ArrayList<Bitmap>();
		imageView1 = (ImageView) view
				.findViewById(R.id.imageView1forphotohandling);
		imageView2 = (ImageView) view
				.findViewById(R.id.imageView2forphotohandling);
		imageView3 = (ImageView) view
				.findViewById(R.id.imageView3forphotohandling);
		imageView4 = (ImageView) view
				.findViewById(R.id.imageView4forphotohandling);
		imageView5 = (ImageView) view
				.findViewById(R.id.imageView5forphotohandling);
		imageView6 = (ImageView) view
				.findViewById(R.id.imageView6forphotohandling);
		imageView7 = (ImageView) view
				.findViewById(R.id.imageView7forphotohandling);
		imageView8 = (ImageView) view
				.findViewById(R.id.imageView8forphotohandling);
		imageView9 = (ImageView) view
				.findViewById(R.id.imageView9forphotohandling);
		imageView10 = (ImageView) view
				.findViewById(R.id.imageView10forphotohandling);

		arraylistforimage = new PhotoHandlingClassNew().sendImage();
		
		try{

		for (int i = 0; i < arraylistforimage.size(); i++) {

			if (i == 0)
				imageView1.setImageBitmap(arraylistforimage.get(i));
			if (i == 1)
				imageView1.setImageBitmap(arraylistforimage.get(i));
			if (i == 2)
				imageView1.setImageBitmap(arraylistforimage.get(i));
			if (i == 3)
				imageView1.setImageBitmap(arraylistforimage.get(i));
			if (i == 4)
				imageView1.setImageBitmap(arraylistforimage.get(i));
			if (i == 5)
				imageView1.setImageBitmap(arraylistforimage.get(i));
			if (i == 5)
				imageView1.setImageBitmap(arraylistforimage.get(i));
			if (i == 6)
				imageView1.setImageBitmap(arraylistforimage.get(i));
			if (i == 7)
				imageView1.setImageBitmap(arraylistforimage.get(i));
			if (i == 8)
				imageView1.setImageBitmap(arraylistforimage.get(i));
			if (i == 9)
				imageView1.setImageBitmap(arraylistforimage.get(i));

			
			
		}
		}catch(Exception selectedIdforadres)
		{}
		try {if (arraylistforimage.size() != 0) {
			arraylistforimage = null;
		}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		

		radiogroupsaletype = (RadioGroup) view
				.findViewById(R.id.radioGroupSalestype);
		radiogroupshowaddress = (RadioGroup) view
				.findViewById(R.id.radioGroupshowaddress);

		startdate = (EditText) view
				.findViewById(R.id.etstartdateformygarbagecreatnew);
		starttime = (EditText) view
				.findViewById(R.id.etstatrtimeformygarbagecreatnew);

		finishtime = (EditText) view
				.findViewById(R.id.etfinishtimeformygarbagecreatnew);
		streetname = (EditText) view
				.findViewById(R.id.etstreetnameformygarbagecreatnew);
		unitstreetnumber = (EditText) view
				.findViewById(R.id.etunitorstreetnumberformygarbagecreatnew);

		suburb = (EditText) view
				.findViewById(R.id.etsuburbformygarbagecreatnew);
		citystarte = (EditText) view
				.findViewById(R.id.etcityformygarbagecreatnew);
		state = (EditText) view.findViewById(R.id.etstateformygarbagecreatnew);
		postcode = (EditText) view
				.findViewById(R.id.etposcodeformygarbagecreatnew);
		discritpion = (EditText) view
				.findViewById(R.id.etdiscriptionformygarbagecreatnew);

		view.findViewById(R.id.imgmygarbagecreatenew).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {

						android.app.FragmentManager fragmentManager = getFragmentManager();
						android.app.FragmentTransaction fragmentTransaction = fragmentManager
								.beginTransaction();

						fragmentTransaction
								.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

						fragmentTransaction.addToBackStack(null);
						fragmentTransaction.replace(R.id.mainfragmentlayout,
								new MygarbageSale());
						fragmentTransaction.commit();

					}
				});

		view.findViewById(R.id.imgsubmitmygarbagecreatnew).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {

						int selectedId = radiogroupsaletype
								.getCheckedRadioButtonId();
						radiobuttonsalestype = (RadioButton) view
								.findViewById(selectedId);
						radiobuttonsalestype.getText();
						int selectedIdforadres = radiogroupshowaddress
								.getCheckedRadioButtonId();
						radiobuttonshowaddress = (RadioButton) view
								.findViewById(selectedIdforadres);

						radiobuttonshowaddress.getText();
						if (startdate.getText().length() != 0
								&& startdate.getText().toString() != "") {

							if (starttime.getText().length() != 0
									&& starttime.getText().toString() != "") {

								if (finishtime.getText().length() != 0
										&& finishtime.getText().toString() != "") {

									if (unitstreetnumber.getText().length() != 0
											&& unitstreetnumber.getText()
													.toString() != "") {

										if (streetname.getText().length() != 0
												&& streetname.getText()
														.toString() != "") {
											if (suburb.getText().length() != 0
													&& suburb.getText()
															.toString() != "") {

												if (citystarte.getText()
														.length() != 0
														&& citystarte.getText()
																.toString() != "") {

													if (state.getText()
															.length() != 0
															&& state.getText()
																	.toString() != "") {

														if (postcode.getText()
																.length() != 0
																&& postcode
																		.getText()
																		.toString() != "") {

															new SubmitInfotoPaypal()
																	.execute();

														} else {
															Toast.makeText(
																	getActivity(),
																	"fill postcode ",
																	Toast.LENGTH_SHORT)
																	.show();

														}

													} else {
														Toast.makeText(
																getActivity(),
																"fill state ",
																Toast.LENGTH_SHORT)
																.show();

													}

												} else {
													Toast.makeText(
															getActivity(),
															"fill citystarte ",
															Toast.LENGTH_SHORT)
															.show();

												}

											} else {
												Toast.makeText(getActivity(),
														"fill suburb ",
														Toast.LENGTH_SHORT)
														.show();
											}

										} else {
											Toast.makeText(getActivity(),
													"fill streetname ",
													Toast.LENGTH_SHORT).show();

										}

									} else {
										Toast.makeText(getActivity(),
												"fill unitstreetnumber ",
												Toast.LENGTH_SHORT).show();

									}

								} else {
									Toast.makeText(getActivity(),
											"fill finishtime ",
											Toast.LENGTH_SHORT).show();

								}

							} else {
								Toast.makeText(getActivity(),
										"fill starttime ", Toast.LENGTH_SHORT)
										.show();

							}

						} else {
							Toast.makeText(getActivity(), "fill startdate ",
									Toast.LENGTH_SHORT).show();

						}
					}
				});
		view.findViewById(R.id.uploadimagemygarbagesalsnew).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// Move to uploading image from camera and gallery

						android.app.FragmentManager fragmentManager = getFragmentManager();
						android.app.FragmentTransaction fragmentTransaction = fragmentManager
								.beginTransaction();

						fragmentTransaction
								.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

						fragmentTransaction.addToBackStack(null);
						fragmentTransaction.replace(R.id.mainfragmentlayout,
								new PhotoHandlingClassNew());
						fragmentTransaction.commit();

						/*
						 * startActivity(new Intent(getActivity(),
						 * PhotoHandlingClassNew.class));
						 */
						// view.finish();
					}
				});

		view.findViewById(R.id.etstartdateformygarbagecreatnew)
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						// Toast.makeText(getActivity(), "hello",
						// Toast.LENGTH_SHORT).show();

						DialogFragment newFragment = new DatePickerFragment();
						newFragment.show(getFragmentManager(), "datePicker");

					}
				});

		starttime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				DialogFragment newFragment = new TimePickerFragment();
				newFragment.show(getFragmentManager(), "timePicker");

			}
		});

		finishtime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				DialogFragment newFragment = new TimePickerFragmentFrofinishtime();
				newFragment.show(getFragmentManager(), "timePicker");

			}
		});
		return view;

	}

	@Override
	public void onResume() {

		super.onResume();

		/*
		 * Bundle extras = getArguments(); Bitmap bmp =
		 * extras.getParcelableArray("Bitmap1");
		 */
	}

	public class DatePickerFragment extends DialogFragment implements
			DatePickerDialog.OnDateSetListener {

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current date as the default date in the picker
			final Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH) + 1;
			int day = c.get(Calendar.DAY_OF_MONTH);

			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}

		public void onDateSet(DatePicker view, int year, int month, int day) {
			// Do something with the date chosen by the user

			Toast.makeText(getActivity(), "date" + month, Toast.LENGTH_SHORT)
					.show();

			startdate.setText(month + "/" + day + "/" + year);

		}
	}

	public class TimePickerFragment extends DialogFragment implements
			TimePickerDialog.OnTimeSetListener {

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current time as the default values for the picker
			final Calendar c = Calendar.getInstance();
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);

			// Create a new instance of TimePickerDialog and return it
			return new TimePickerDialog(getActivity(), this, hour, minute,
					DateFormat.is24HourFormat(getActivity()));
		}

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// Do something with the time chosen by the user
			starttime.setText(hourOfDay + ":" + minute);
			// finishtime.setText

		}
	}

	public class TimePickerFragmentFrofinishtime extends DialogFragment
			implements TimePickerDialog.OnTimeSetListener {

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current time as the default values for the picker
			final Calendar c = Calendar.getInstance();
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);

			// Create a new instance of TimePickerDialog and return it
			return new TimePickerDialog(getActivity(), this, hour, minute,
					DateFormat.is24HourFormat(getActivity()));
		}

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// Do something with the time chosen by the user
			finishtime.setText(hourOfDay + ":" + minute);
			// finishtime.setText

		}

		@Override
		public void onResume() {

			super.onResume();

		}
	}

	private class SubmitInfotoPaypal extends AsyncTask<String, String, Void> {

		double lat;

		double lon;

		private ProgressDialog pDialog;
		private final String URL = "http://garagesalesagogo.com.au/ProductService.asmx?op=AddProducts";
		private final String SOAP_ACTION = "http://tempuri.org/AddProducts";
		private String TAG = "PGGURU";

		@Override
		protected Void doInBackground(String... params) {
			Log.i(TAG, "I am in doInBackground");
			SoapObject addProducts = null;
			SoapObject prd = null;
			SoapObject productImages = null;
			// SoapObject productImagesURL = null;
			SoapObject goodsType = null;
			SoapObject status = null;
			SoapObject locationofitem = null;
			/*
			 * SoapObject createdBy = null; SoapObject userImage = null;
			 * SoapObject loginStatus = null; SoapObject locationofUser = null;
			 */

			// Create request

			addProducts = new SoapObject("http://tempuri.org/", "AddProducts");
			prd = new SoapObject("http://tempuri.org/", "prd");
			// prd.addProperty("ProductId", 12);
			/*
			 * productImages = new SoapObject("http://tempuri.org/",
			 * "ProductImages");
			 */
			productImages = new SoapObject("prd", "ProductImages");
			productImages.addProperty("string", "jnndfjnf");

			prd.addSoapObject(productImages);

			prd.addProperty("GarageSaleTitle", null);
			prd.addProperty("StartDate", startdate.getText().toString());
			prd.addProperty("OneOrTwoDaySale", radiobuttonsalestype.getText());
			prd.addProperty("SaleStartTime", starttime.getText().toString());
			prd.addProperty("SaleFinishTime", finishtime.getText().toString());
			prd.addProperty("UnitStreeNo", unitstreetnumber.getText()
					.toString());
			prd.addProperty("StreeName", streetname.getText().toString());
			prd.addProperty("Suburb", suburb.getText().toString());
			prd.addProperty("City", citystarte.getText().toString());
			prd.addProperty("State", state.getText().toString());
			prd.addProperty("PostCode", postcode.getText().toString());
			prd.addProperty("Description", discritpion.getText().toString());
			prd.addProperty("EarlyBirdMessage", 0);
			prd.addProperty("BadWeatherMessage", 0);

			String address = streetname.getText() + " " + citystarte.getText()
					+ " " + state.getText();
			/*
			 * goodsType = new SoapObject("http://tempuri.org/", "GoodsType");
			 */goodsType = new SoapObject("prd", "GoodsType");

			goodsType.addProperty("string", 1);
			goodsType.addProperty("string", 1);
			goodsType.addProperty("string", 1);
			goodsType.addProperty("string", 1);
			prd.addSoapObject(goodsType);

			status = new SoapObject("prd", "Status");
			status.addProperty("Status", 1);
			status.addProperty("Message", "hello");
			prd.addSoapObject(status);

			// getting the userId form DB
			UserInfoCRUD userInfoCRUD = new UserInfoCRUD(getActivity());
			ArrayList<String> userinfo = userInfoCRUD.getAllData();
			String[] ar = new String[13];
			for (int i = 0; i < userinfo.size(); i++) {

				ar[i] = userinfo.get(i);

			}

			prd.addProperty("CurrentUser", ar[12]);
			getLatLongFromGivenAddress(address);
			locationofitem = new SoapObject("prd", "Location");
			locationofitem.addProperty("Longitude", String.valueOf(lon));
			locationofitem.addProperty("Latitude", String.valueOf(lat));
			prd.addSoapObject(locationofitem);
			addProducts.addSoapObject(prd);

			// Create envelope
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.dotNet = true;
			// Set output SOAP object
			envelope.setOutputSoapObject(addProducts);
			envelope.implicitTypes = true;
			// Create HTTP call object
			HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
			SoapObject addProductsResponse = null;
			SoapObject addProductsResultobj = null;
			SoapObject statusobj = null;

			try {
				// Invole web service
				androidHttpTransport.call(SOAP_ACTION, envelope);
				// Get the response

				addProductsResponse = (SoapObject) envelope.bodyIn;

				addProductsResultobj = (SoapObject) addProductsResponse
						.getProperty(0);
				/*
				 * String productId = addProductsResultobj
				 * .getPropertyAsString("ProductId");
				 */
				statusobj = (SoapObject) addProductsResultobj.getProperty(1);
				statusof = statusobj.getPropertyAsString("Status");
				mesageof = statusobj.getPropertyAsString("Message");

			} catch (Exception e) {
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPreExecute() {
			Log.i(TAG, "I am in onPreExecute");
			// Showing progress dialog

			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Please wait for match List...");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected void onProgressUpdate(String... values) {
			Log.i(TAG, "Im am in onProgressUpdate");

		}

		@Override
		protected void onPostExecute(Void result) {

			pDialog.dismiss();
			Log.i(TAG, "I am in onPostExecute");

			if ((statusof.equals("true")) && (mesageof.equals("Success"))) {

				Toast.makeText(getActivity(), "Data is saved",
						Toast.LENGTH_LONG).show();

				startActivity(new Intent(getActivity(), MainPaypalclass.class));

				android.app.FragmentManager fragmentManager = getFragmentManager();
				android.app.FragmentTransaction fragmentTransaction = fragmentManager
						.beginTransaction();

				fragmentTransaction
						.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

				fragmentTransaction.addToBackStack(null);
				fragmentTransaction.replace(R.id.mainfragmentlayout,
						new MyHomePage());
				fragmentTransaction.commit();

			} else {
				Toast.makeText(getActivity(), "Errorr in saving Data",
						Toast.LENGTH_LONG).show();

			}

		}

		public void getLatLongFromGivenAddress(String youraddress) {
			String uri = "http://maps.google.com/maps/api/geocode/json?address="
					+ youraddress + "&sensor=false";
			HttpGet httpGet = new HttpGet(uri);
			HttpClient client = new DefaultHttpClient();
			HttpResponse response;
			StringBuilder stringBuilder = new StringBuilder();

			try {
				response = client.execute(httpGet);
				HttpEntity entity = response.getEntity();
				InputStream stream = entity.getContent();
				int b;
				while ((b = stream.read()) != -1) {
					stringBuilder.append((char) b);
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			JSONObject jsonObject = new JSONObject();
			try {
				jsonObject = new JSONObject(stringBuilder.toString());

				lon = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
						.getJSONObject("geometry").getJSONObject("location")
						.getDouble("lng");

				lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
						.getJSONObject("geometry").getJSONObject("location")
						.getDouble("lat");

				Log.d("latitude", "latitute" + lat);
				Log.d("longitude", "longitute" + lon);
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

	}

}
